const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require("path");
const jpath = path.join(__dirname,"..","json","logmes.json");
const mpath = path.join(__dirname,"..","json","postmes.json");

const PW = require("png-word");
const pw = new PW();
const R = require("random-word");

/* GET users listing. */
router.get("/vimg", function(req, res) {
  var r = new R("0123456789");
  req.session.vimg = r.random(4);
  pw.createReadStream(req.session.vimg).pipe(res);
});

router.get('/login', function(req, res, next) {
  req.session.firstnum = res.locals.firstnum = Math.round(Math.random() * 10);
  req.session.secondnum = res.locals.secondnum = Math.round(Math.random() * 10);
  return res.render("login");
});

router.get('/reg', function(req, res, next) {
  return res.render("reg");
});

router.post("/reg", function(req, res) {
  const {
    loginname,
    password,
    confirm,
    vimg
  } = req.body;

//读取注册文件信息，得到已注册的用户名
  try {
      var data = fs.readFileSync(jpath,"utf8");
      console.log("读取文件成功。");
      // console.log(data);
  } catch(err) {
      console.log("读取文件时发生错误。");
  };

  if (data){
    var users = JSON.parse(data);
    var logednames = Object.keys(users);
    // console.log(logednames);
  };

  for(j = 0,len=logednames.length; j < len; j++) {
    if (loginname == logednames[j]) {
      console.log("此用户名已注册，请重新注册。");
      return res.redirect("back");
    }
  };

//注册条件验证（简略条件）
  if (req.session.vimg === vimg
    && loginname > 2 && password > 2 && password === confirm) {
    res.locals.user = req.session.user = users[loginname] = {
      loginname,
      password,
    };
    // console.log(users);
    fs.writeFileSync(jpath,JSON.stringify(users));
    console.log("注册成功");
    // console.log(res.locals.user);


//读取留言文件信息，得到所有用户的留言
    try {
        var data = fs.readFileSync(mpath,"utf8");
        console.log("读取文件成功。");
        // console.log("data=");
        // console.log(data);
    } catch(err) {
        console.log("读取文件时发生错误。");
    };

    if (data){
      var meses = JSON.parse(data);
    }else{
      var meses = {};
    };
    req.session.meses = res.locals.meses = meses;

    req.session.firstnum = res.locals.firstnum = Math.round(Math.random() * 10);
    req.session.secondnum = res.locals.secondnum = Math.round(Math.random() * 10);
    res.render("loged");
  }else{
    // console.log(req.body);
    console.log("注册失败，请重新注册");
    return res.redirect("back");
  };
});

router.post("/login", function(req, res) {
  const {
    loginname,
    password,
    vnum
  } = req.body;

  //读取注册文件信息，得到已注册的用户名
  try {
      var data = fs.readFileSync(jpath,"utf8");
      console.log("读取文件成功。");
      // console.log(data);
  } catch(err) {
      console.log("读取文件时发生错误。");
  };

  if (data){
    var users = JSON.parse(data);
    var logednames = Object.keys(users);
    // console.log(logednames);
  };

  // console.log(users[loginname]);

//登录验证
  if (
    Number(vnum) === req.session.firstnum + req.session.secondnum &&
    users[loginname] &&
    users[loginname].password === password) {
    req.session.user = {
      loginname
    }
  }
  // console.log(req.session.user);
  res.locals.user = req.session.user;

//读取留言文件信息，得到所有用户的留言
  try {
      var data = fs.readFileSync(mpath,"utf8");
      console.log("读取文件成功。");
      // console.log("data=");
      // console.log(data);
  } catch(err) {
      console.log("读取文件时发生错误。");
  };

  if (data){
    var meses = JSON.parse(data);
  }else{
    var meses = {};
  };
  req.session.meses = res.locals.meses = meses;

  req.session.firstnum = res.locals.firstnum = Math.round(Math.random() * 10);
  req.session.secondnum = res.locals.secondnum = Math.round(Math.random() * 10);
  res.render("loged");
});

router.use("/up", function(req, res) {
  const {
    content,
    vnum
  } = req.body;
  console.log(req.body);
  res.locals.user = req.session.user;
  var loginname = res.locals.user.loginname;
  console.log(loginname);

// 读取留言文件信息，得到所有用户的留言
  try {
      var data = fs.readFileSync(mpath,"utf8");
      console.log("读取文件成功。");
      console.log("data=");
      console.log(data);
  } catch(err) {
      console.log("读取文件时发生错误。");
  };

  if (data){
    var meses = JSON.parse(data);
  }else{
    var meses = {};
  };

  var curDT = new Date().toLocaleString();//获取系统当前时间
  var loginname = res.locals.user.loginname;

//发布留言验证及上传
  if (
    Number(vnum) === req.session.firstnum + req.session.secondnum) {
      // meses[curDT][loginname] = content;
    meses[curDT] = {
      loginname,
      content
    };
    fs.writeFileSync(mpath,JSON.stringify(meses));
    console.log("留言存入成功");
  }else{
    console.log("留言存入失败，请重新留言");
  };

  req.session.meses = res.locals.meses = meses;
  console.log("req.session.meses=");
  console.log(req.session.meses);
  // console.log(logednames);Object.keys(meses);
  req.session.firstnum = res.locals.firstnum = Math.round(Math.random() * 10);
  req.session.secondnum = res.locals.secondnum = Math.round(Math.random() * 10);
  res.render("loged");
});

router.get("/logout", function(req, res) {
  req.session.user = undefined;

// 读取留言文件信息，得到所有用户的留言
  try {
      var data = fs.readFileSync(mpath,"utf8");
      console.log("读取文件成功。");
      console.log("data=");
      console.log(data);
  } catch(err) {
      console.log("读取文件时发生错误。");
  };

  if (data){
    var meses = JSON.parse(data);
  }else{
    var meses = {};
  };

  req.session.meses = res.locals.meses = meses;
  res.render("index");
});

module.exports = router;
